import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import LoginView from '../views/common/LoginView.vue'
import RegisterView from '../views/common/RegisterView.vue'
import ForgotPasswordView from '../views/common/ForgotPasswordView.vue'
import Layout from '../components/common/Layout.vue'
import DashboardView from '../views/guard/DashboardView.vue'
import AdminDashboardView from '../views/admin/AdminDashboardView.vue'
import SuperAdminDashboardView from '../views/super-admin/SuperAdminDashboardView.vue'
import QRCodeVerificationView from '../views/guard/QRCodeVerificationView.vue'
import TodaysRecordsView from '../views/guard/TodaysRecordsView.vue'

// 定义路由类型
export const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      requiresAuth: false,
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: {
      requiresAuth: false,
      title: '注册'
    }
  },
  {
    path: '/forgot-password',
    name: 'forgot-password',
    component: ForgotPasswordView,
    meta: {
      requiresAuth: false,
      title: '找回密码'
    }
  },
  // 守卫用户路由
  {
    path: '/',
    component: Layout,
    meta: {
      requiresAuth: true,
      roles: ['guard']
    },
    children: [
      {
        path: '',
        name: 'dashboard',
        component: DashboardView,
        meta: {
          title: '仪表盘'
        }
      },
      {
        path: 'qrcode-verification',
        name: 'qrcode-verification',
        component: QRCodeVerificationView,
        meta: {
          title: '二维码验证'
        }
      },
      {
        path: 'todays-records',
        name: 'todays-records',
        component: TodaysRecordsView,
        meta: {
          title: '今日记录查询'
        }
      }
    ]
  },
  // 管理员路由
  {
    path: '/admin',
    component: Layout,
    meta: {
      requiresAuth: true,
      roles: ['admin']
    },
    children: [
      {
        path: '',
        name: 'admin-dashboard',
        component: AdminDashboardView,
        meta: {
          title: '管理员仪表盘'
        }
      }
    ]
  },
  // 超级管理员路由
  {
    path: '/super-admin',
    component: Layout,
    meta: {
      requiresAuth: true,
      roles: ['super-admin']
    },
    children: [
      {
        path: '',
        name: 'super-admin-dashboard',
        component: SuperAdminDashboardView,
        meta: {
          title: '超级管理员仪表盘'
        }
      }
    ]
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, _, next) => {
  // 设置页面标题
  const title = to.meta.title as string || '新易访内网系统'
  document.title = title
  
  // 检查是否需要登录
  const isAuthenticated = !!localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router